<script setup lang="ts">
import { getCommunityTagList, getArticleList, likeArticle, cancelLikeArticle } from '@/api/community';
import { getUserInfoById } from '@/api/user';
import { Article } from '@/api/community/type';
import { Tag } from '@/api/system/tag/type';
import { User } from '@/api/user/type';
import { onMounted, Ref, ref, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { showSuccessToast, showFailToast, showNotify } from 'vant';
import { formatRelativeTime } from '@/utils/time';

interface ArticleWithAuthor extends Article {
  user?: User;
}

const router = useRouter();
const communityId = defineModel() as Ref<string>;
const tagList = ref<Tag[]>([]);
const allArticles = ref<ArticleWithAuthor[]>([]);
const active = ref(0);
const loading = ref(true);
const refreshing = ref(false);

// 监听社区ID变化，重新获取数据
watch(() => communityId.value, (newId) => {
  if (newId) {
    loadData();
  }
});

// 加载所有数据
const loadData = async () => {
  try {
    loading.value = true;
    
    // 获取标签列表
    const tagRes = await getCommunityTagList(communityId.value);
    tagList.value = tagRes.data as Tag[];
    
    if (tagList.value.length > 0) {
      // 获取文章列表
      await fetchArticles();
    }
  } catch (error) {
    console.error('加载社区数据失败:', error);
    showNotify({
      type: 'danger',
      message: '加载社区数据失败',
      position: 'top'
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 获取文章列表
const fetchArticles = async () => {
  try {
    const articlesRes = await getArticleList(communityId.value);
    const articles = articlesRes.data || [];
    
    // 批量获取作者信息
    const articlesWithUsers = await Promise.all(
      articles.map(async (article: Article) => {
        try {
          const userRes = await getUserInfoById(article.authorId);
          return {
            ...article,
            user: userRes.data
          } as ArticleWithAuthor;
        } catch (error) {
          console.error('获取用户信息失败:', error);
          return {
            ...article
          } as ArticleWithAuthor;
        }
      })
    );
    
    allArticles.value = articlesWithUsers;
  } catch (error) {
    console.error('获取文章列表失败:', error);
    showNotify({
      type: 'danger',
      message: '获取文章列表失败',
      position: 'top'
    });
  }
};

// 根据当前选中的标签筛选文章
const filteredArticles = computed(() => {
  if (tagList.value.length === 0) return [];
  const currentTagId = tagList.value[active.value]?.id;
  if (!currentTagId) return [];
  return allArticles.value.filter(article => article.tagId === currentTagId);
});

// 处理标签切换
const handleTabChange = (index: number) => {
  active.value = index;
};

// 刷新数据
const onRefresh = async () => {
  refreshing.value = true;
  await fetchArticles();
  refreshing.value = false;
};

// 处理点赞
const likeDebounce = ref<{[key: string]: {timestamp: number, processing: boolean}}>({});

const handleLikeToggle = async (article: ArticleWithAuthor, event: Event) => {
  event.stopPropagation();
  
  const articleId = article.id;
  const now = Date.now();
  
  // 防抖处理
  if (likeDebounce.value[articleId]) {
    if (likeDebounce.value[articleId].processing) {
      return;
    }
    
    const lastTime = likeDebounce.value[articleId].timestamp;
    if (now - lastTime < 500) {
      showFailToast('操作太频繁，请稍后再试');
      return;
    }
  }
  
  likeDebounce.value[articleId] = {
    timestamp: now,
    processing: true
  };
  
  // 乐观更新UI
  const originalLiked = article.isLike;
  const originalLikeCount = article.likeCount || '0';
  
  if (originalLiked) {
    article.isLike = false;
    article.likeCount = String(Math.max(0, parseInt(originalLikeCount) - 1));
  } else {
    article.isLike = true;
    article.likeCount = String(parseInt(originalLikeCount) + 1);
  }
  
  try {
    if (originalLiked) {
      await cancelLikeArticle(articleId);
    } else {
      await likeArticle(articleId);
    }
  } catch (error) {
    // 恢复原状态
    article.isLike = originalLiked;
    article.likeCount = originalLikeCount;
    console.error('点赞操作失败:', error);
  } finally {
    if (likeDebounce.value[articleId]) {
      likeDebounce.value[articleId].processing = false;
    }
  }
};

// 跳转到文章详情
const navigateToArticleDetail = (articleId: string) => {
  router.push({
    name: 'CommunityArticleDetail',
    params: { id: articleId }
  });
};

// 跳转到评论
const goToComments = (articleId: string, event: Event) => {
  event.stopPropagation();
  router.push({
    name: 'CommunityArticleDetail',
    params: { id: articleId }
  });
};

// 分享文章
const shareArticle = (article: ArticleWithAuthor, event: Event) => {
  event.stopPropagation();
  // 实现分享功能
  navigator.clipboard.writeText(window.location.origin + `/community/article/${article.id}`);
  showSuccessToast('链接已复制到剪贴板');
};

// 截取内容预览
const getContentPreview = (content: string, maxLength: number = 100) => {
  if (!content) return '';
  if (content.length <= maxLength) return content;
  return content.substring(0, maxLength) + '...';
};

onMounted(() => {
  if (communityId.value) {
    loadData();
  }
});
</script>

<template>
  <div class="community-tabs-container">
    <van-tabs 
      v-model:active="active" 
      @change="handleTabChange"
      swipeable
      animated
      sticky
      color="#1989fa"
      title-active-color="#1989fa"
      background="#fff"
    >
      <van-tab 
        v-for="item in tagList" 
        :key="item.id" 
        :title="item.name"
      >
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="tab-content">
          <div v-if="loading && !refreshing" class="loading-state">
            <van-loading type="spinner" size="24px" vertical>加载中...</van-loading>
          </div>
          
          <div v-else-if="filteredArticles.length === 0" class="empty-state">
            <van-empty image="search" description="暂无文章">
              <template #default>
                <p class="empty-tip">成为第一个发帖的人吧!</p>
              </template>
            </van-empty>
          </div>
          
          <div v-else class="article-list">
            <div 
              v-for="article in filteredArticles" 
              :key="article.id" 
              class="article-card"
              @click="navigateToArticleDetail(article.id)"
            >
              <!-- 作者信息 -->
              <div class="article-author">
                <van-image 
                  round 
                  width="40" 
                  height="40"
                  :src="article.user?.avatar"
                  fit="cover"
                  class="author-avatar"
                />
                
                <div class="author-info">
                  <div class="author-name">{{ article.user?.nickname || '未知用户' }}</div>
                  <div class="post-time">{{ formatRelativeTime(article.created || '') }}</div>
                </div>
              </div>
              
              <!-- 文章内容 -->
              <div class="article-content">
                <p class="article-text">{{ getContentPreview(article.content) }}</p>
              </div>
              
              <!-- 文章操作 -->
              <div class="article-actions">
                <div class="action-button" @click.stop="handleLikeToggle(article, $event)">
                  <van-icon 
                    :name="article.isLike ? 'like' : 'like-o'"
                    :class="{ 'liked': article.isLike }"
                  />
                  <span>{{ article.likeCount || '0' }}</span>
                </div>
                
                <div class="action-button" @click.stop="goToComments(article.id, $event)">
                  <van-icon name="comment-o" />
                  <span>{{ article.commentCount || '0' }}</span>
                </div>
                
                <div class="action-button" @click.stop="shareArticle(article, $event)">
                  <van-icon name="share-o" />
                  <span>分享</span>
                </div>
              </div>
            </div>
          </div>
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
  </div>
</template>

<style lang="scss" scoped>
.community-tabs-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .tab-content {
    min-height: 300px;
    flex: 1;
    background-color: #f7f8fa;
  }
  
  .loading-state,
  .empty-state {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 40px 0;
    
    .empty-tip {
      margin-top: 16px;
      color: #969799;
      font-size: 14px;
    }
  }
  
  .article-list {
    padding: 16px;
    
    .article-card {
      background-color: #fff;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
      }
      
      .article-author {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        
        .author-avatar {
          margin-right: 12px;
        }
        
        .author-info {
          flex: 1;
          
          .author-name {
            font-weight: 500;
            font-size: 15px;
            color: #323233;
            margin-bottom: 2px;
          }
          
          .post-time {
            font-size: 12px;
            color: #969799;
          }
        }
      }
      
      .article-content {
        margin-bottom: 16px;
        
        .article-text {
          margin: 0;
          font-size: 15px;
          line-height: 1.5;
          color: #323233;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 3;
          word-break: break-word;
        }
      }
      
      .article-actions {
        display: flex;
        border-top: 1px solid rgba(0, 0, 0, 0.05);
        padding-top: 12px;
        
        .action-button {
          display: flex;
          align-items: center;
          justify-content: center;
          flex: 1;
          padding: 8px 0;
          cursor: pointer;
          transition: all 0.2s;
          border-radius: 4px;
          
          &:hover {
            background-color: rgba(0, 0, 0, 0.03);
          }
          
          .van-icon {
            font-size: 16px;
            margin-right: 4px;
            
            &.liked {
              color: #ee0a24;
            }
          }
          
          span {
            font-size: 14px;
            color: #646566;
          }
        }
      }
    }
  }
}
</style>